class Solution{
    vector<int> spiralOrder(vector<vector<int> > &matrix) {
        vector<int> v;
        int ml = 0, mh = matrix.size()-1;
        if(ml>mh) return v;
        int nl = 0, nh = matrix[0].size()-1;
        int i = 0, j = 0;

        while(true) {
            while(j<=nh) v.push_back(matrix[i][j++]);
            j--;
            i++;
            ml++;
            if(ml>mh || nl>nh) return v;
            while(i<=mh) v.push_back(matrix[i++][j]);
            i--;
            j--;
            nh--;
            if(ml>mh || nl>nh) return v;
            while(j>=nl) v.push_back(matrix[i][j--]);
            j++;
            i--;
            mh--;
            if(ml>mh || nl>nh) return v;
            while(i>=ml) v.push_back(matrix[i--][j]);
            i++;
            j++;
            nl++;
            if(ml>mh || nl>nh) return v;
        }
        return v;
    }
};
